package com.liang.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.liang.gulimall.product.service.CategoryBrandRelationService;
import com.liang.gulimall.product.vo.Category2Vo;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.common.utils.PageUtils;
import com.liang.common.utils.Query;

import com.liang.gulimall.product.dao.CategoryDao;
import com.liang.gulimall.product.entity.CategoryEntity;
import com.liang.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.xml.bind.annotation.XmlEnum;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = categoryDao.selectList(null);

        //2、组装成父子的树形结构
        //2.1找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{
            menu.setChildren(getChildren(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单是否被别的地方引用
        //逻辑删除
        categoryDao.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCategoryPath(Long catelogId) {
        List<Long> paths=new ArrayList<>();
        List<Long> path = findParentPath(catelogId, paths);
        Collections.reverse(path);

        return path.toArray(new Long[path.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     * @CacheEvict:更新数据库的数据后，删除缓存
     * @CacheEvict(value = "category",allEntries = true) :删除某个分区下所有数据
     */
//    @CacheEvict(value = "category",key = "'level1Category'")
//    @Caching(evict = {//方式1、组合多个操作
//            @CacheEvict(value = "category",key = "'level1Category'"),
//            @CacheEvict(value = "category",key = "'getCategoryJson'")
//    })
    //方式2
    @CacheEvict(value = "category",allEntries = true)//失效模式
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }


    /**
     * @Cacheable:
     * 当前方法的结果需要缓存。如果缓存中有则不需要调用方法，没有则调用方法，并把结果放到缓存中
     * 每个缓存数据都需要指定放到哪个分区(可以指定多个分区)，category
     *  默认过期时间-1，永不过期
     *  缓存的key默认自动生成，
     * 	默认使用jdk序列化机制
     * 	spel:https://docs.spring.io/spring-framework/docs/5.0.20.RELEASE/spring-framework-reference/integration.html#cache
     * 	自定义：key(key属性指定)、过期时间（配置文件中指定）、json序列化器（自定义RedisCacheConfiguration类设置）
     * @return
     */
    @Cacheable(value = "category",key = "'level1Category'")
    @Override
    public List<CategoryEntity> getLevel1Category() {
        System.out.println("getLevel1Category调用了----------------");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        return categoryEntities;
    }

    /**
     * 最终使用spring cache一个注解搞定
     * @return
     */
    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Category2Vo>> getCategoryJson() {
        System.out.println("正在查数据库===============");
        /**
         * 优化：将多次查查数据库变为一次
         */
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //1、查出一级分类
        List<CategoryEntity> level1Category = getCategoryLevelByParentCid(categoryEntities, 0L);
        //2封装数据
        Map<String, List<Category2Vo>> categoryJson = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查到此一级分类的二级分类
            List<CategoryEntity> category2Entities = getCategoryLevelByParentCid(categoryEntities, v.getCatId());
            List<Category2Vo> collect = null;
            if (category2Entities != null) {
                collect = category2Entities.stream().map(item2 -> {
                    //查到此2级分类的3级分类
                    List<CategoryEntity> category3Entities = getCategoryLevelByParentCid(categoryEntities, item2.getCatId());
                    List<Category2Vo.Category3Vo> collect1 = null;
                    if (category3Entities != null) {
                        collect1 = category3Entities.stream().map(item3 -> {
                            Category2Vo.Category3Vo category3Vo = new Category2Vo.Category3Vo(item2.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                    }

                    Category2Vo category2Vo = new Category2Vo(v.getCatId().toString(), collect1, item2.getCatId().toString(), item2.getName());
                    return category2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        return categoryJson;
    }

    /**
     * TODO io.netty.util.internal.OutOfDirectMemoryError Redis造成对外内存溢出底层使用的lettuce不稳定
     *
     * @return
     */
    public Map<String, List<Category2Vo>> getCategoryJson2() {
        /**
         * 1、空结果缓存:解决缓存穿透
         * 2、设置过期时间(加随机值)︰解决缓存雪崩
         * 3、加锁。解决缓存击穿
         */
        //使用缓存
        String categoryJson = redisTemplate.opsForValue().get("categoryJson");
        if (StringUtils.isEmpty(categoryJson)){
            //缓存中没有，从数据库查
            System.out.println("缓存不命中——————————————————————————————————————————开始查数据库-----");
             Map<String, List<Category2Vo>> categoryJsonFromDb = getCategoryJsonFromDbWithRedissonLock();//加锁，确保只有一个线程查数据库
            //放入缓存，方便下次查,对象要转为json串(跨语言，跨平台)
//            String json = JSON.toJSONString(categoryJsonFromDb);放入缓存需要时间，还会有线程查数据库，所以不在这放缓存
//            redisTemplate.opsForValue().set("categoryJson",json,1, TimeUnit.DAYS);//并设置过期时间1天
            return categoryJsonFromDb;
        }
        //缓存中有，先转为对象再返回，new TypeReference<>() 传入要返回的类型
        System.out.println("缓存命中-----------------------直接返回----");
        Map<String, List<Category2Vo>> result = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Category2Vo>>>() {
        });
        return result;
    }

    /**
     * 方案1：本地锁
     * 枷锁synchronized容器中所有组件都是单例的，可以满足只有一人进来拿到锁
     * TODO synchronized本地锁，只能锁当前进程，分布式下不适用，
     *
     * @return
     */
    private synchronized Map<String, List<Category2Vo>> getCategoryJsonFromDbWithLocalLock() {
        //获得锁还要查一下缓存
        return getDataFromDb();
    }

    /**
     * 方案2：分布式锁
     * @return
     */
    private  Map<String, List<Category2Vo>> getCategoryJsonFromDbWithRedisLock() {
        //占分布式锁，去redis占坑,并设置过期时间，防止来不及删锁
        String uuid = UUID.randomUUID().toString();
        Boolean local = redisTemplate.opsForValue().setIfAbsent("local", uuid,30,TimeUnit.SECONDS);
        if (local){
            //加锁成功
            System.out.println("获取锁成功。。。。。。。。。。。。");
            redisTemplate.expire("local",30,TimeUnit.SECONDS);
            Map<String, List<Category2Vo>> dataFromDb;
            try{
                dataFromDb = getDataFromDb();
            }finally {
                //删除锁,删自己的锁，（取值对比+删除=原子操作） ，使用lua脚本解锁
            /*
            不能保证原子性
            String localValue = redisTemplate.opsForValue().get("local");
            if (uuid.equals(localValue)){
                redisTemplate.delete("local");
            }
            */
                String lua="if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<>(lua,Integer.class),Arrays.asList("local"),uuid);
            }
            return dataFromDb;
        }else {
            System.out.println("获取锁失败。。。。。。。。。。。。重试");
            //加锁失败,自旋方式
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCategoryJsonFromDbWithRedisLock();
        }

    }
    /**
     * 方案3：分布式锁Redisson实现
     * TODO 缓存里面的数据如何与数据库保持一致，缓存一致性
     * 1、双写模式：修改数据库后再修改缓存
     * 2、失效模式：写数据库后删缓存
     * @return
     */
    private  Map<String, List<Category2Vo>> getCategoryJsonFromDbWithRedissonLock() {
        RLock lock = redissonClient.getLock("categoryJson-lock");
        lock.lock();
        Map<String, List<Category2Vo>> dataFromDb;
        try{
            dataFromDb = getDataFromDb();
        }finally {
            lock.unlock();
        }
        return dataFromDb;


    }

    /**
     * 查数据，先去缓存，没有再去数据库
     * 从数据库查的数据，并封装.用于首页的三级分类渲染
     * @return
     */
    private Map<String, List<Category2Vo>> getDataFromDb() {
        String categoryJsonFromRedis = redisTemplate.opsForValue().get("categoryJson");
        if (!StringUtils.isEmpty(categoryJsonFromRedis)) {
            //有数据了直接返回
            Map<String, List<Category2Vo>> result = JSON.parseObject(categoryJsonFromRedis, new TypeReference<Map<String, List<Category2Vo>>>() {
            });
            System.out.println("-----------------获得锁在查数据库之前并命中了----------------------");
            return result;
        }
        System.out.println("正在查数据库---------=======================================");
        /**
         * 优化：将多次查查数据库变为一次
         */
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //1、查出一级分类
        List<CategoryEntity> level1Category = getCategoryLevelByParentCid(categoryEntities, 0L);
        //2封装数据
        Map<String, List<Category2Vo>> categoryJson = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查到此一级分类的二级分类
            List<CategoryEntity> category2Entities = getCategoryLevelByParentCid(categoryEntities, v.getCatId());
            List<Category2Vo> collect = null;
            if (category2Entities != null) {
                collect = category2Entities.stream().map(item2 -> {
                    //查到此2级分类的3级分类
                    List<CategoryEntity> category3Entities = getCategoryLevelByParentCid(categoryEntities, item2.getCatId());
                    List<Category2Vo.Category3Vo> collect1 = null;
                    if (category3Entities != null) {
                        collect1 = category3Entities.stream().map(item3 -> {
                            Category2Vo.Category3Vo category3Vo = new Category2Vo.Category3Vo(item2.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                    }

                    Category2Vo category2Vo = new Category2Vo(v.getCatId().toString(), collect1, item2.getCatId().toString(), item2.getName());
                    return category2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        //放入缓存，方便下次查,对象要转为json串(跨语言，跨平台)
        //数据库查完后立刻放进缓存，真正的只有一个线程查了数据库
        String json = JSON.toJSONString(categoryJson);
        redisTemplate.opsForValue().set("categoryJson", json, 1, TimeUnit.DAYS);//并设置过期时间1天

        return categoryJson;
    }



    private List<CategoryEntity> getCategoryLevelByParentCid(List<CategoryEntity> categoryEntities,Long parent_cid) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;

    }

    private  List<Long> findParentPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);

        CategoryEntity byId = this.getById(catelogId);
        System.out.println(byId.getParentCid()+",-----byId.getParentCid()");
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }



    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> child = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //找到子菜单
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());


        return child;
    }

}